package framework.core.popup
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.geom.Point;
import flash.system.Capabilities;
import flash.utils.Dictionary;

import framework.view.components.Component;

public class DefaultPopUpProxy implements IPopUpProxy
{
	private var popUpPool:Dictionary = new Dictionary(true);
	private var container:DisplayObjectContainer;
	
	private var stageW:Number;
	private var stageH:Number;
	private var screenW:Number;
	private var screenH:Number;
	
	public function initialize(container:DisplayObjectContainer):void
	{
		this.container = container;
		if (container.stage)
		{
			addToStageHandler(null);
		}
		else
		{
			container.addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		}
	}
	
	private function addToStageHandler(event:FullScreenEvent):void
	{
		container.removeEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		
		stageW = container.stage.stageWidth;
		stageH = container.stage.stageHeight;
		
		screenW = Capabilities.screenResolutionX;
		screenH = Capabilities.screenResolutionY;
	}
	
	public function show(displayObj:DisplayObject, centre:Boolean=true, position:Point=null, lock:Boolean=false, ...args):void
	{
		if (popUpPool[displayObj] != null) return;
		
		popUpPool[displayObj] = { popUp:displayObj, lock:null };
		
		if (centre)
		{
			displayObj.x = (stageW - displayObj.width) / 2;
			displayObj.y = (stageH - displayObj.height) / 2;
		}
		else if (position)
		{
			displayObj.x = position.x;
			displayObj.y = position.y;
		}
		
		if (lock)
		{			
			var lockSP:Sprite = new Sprite();
			lockSP.graphics.beginFill(0, 0);
			lockSP.graphics.drawRect((stageW - screenW)/2 , 
													(stageH - screenH)/2, 
													screenW, 
													screenH);
			lockSP.graphics.endFill();
			container.addChild(lockSP);
			popUpPool[displayObj].lock = lockSP;
		}
		container.addChild(displayObj);
	}
	
	public function close(displayObj:DisplayObject):void
	{
		if (popUpPool[displayObj] != null)
		{
			var oldPopUp:DisplayObject = popUpPool[displayObj].popUp;
			var oldLock:DisplayObject = popUpPool[displayObj].lock;
			
			delete popUpPool[displayObj];
			
			if (oldPopUp && container.contains(oldPopUp))
			{
				container.removeChild(oldPopUp);
				/*
				if (oldPopUp is Component)
				{
					Component(oldPopUp).dispose();
				}
				else if (oldPopUp.hasOwnProperty("dispose"))
				{
					oldPopUp["dispose"]();
				}
				*/
				oldPopUp = null;    			
			}
			
			if (oldLock && container.contains(oldLock))
			{
				container.removeChild(oldLock);
				oldLock = null;    			
			}
		}
	}
}
}